import json

import jmespath
import requests
from faker import Faker

from aaa import outer
from loguru import logger


@outer
def login():
    headers = {'content-type': 'application/json'}
    json_data = {'account': 'demo', 'pwd': 'crmeb.com', 'captchaVO': {}, }
    url = 'https://api.admin.merchant.java.crmeb.net/api/admin/platform/login'
    response = requests.post(url, headers=headers, json=json_data, )
    return response.json()


class BaseFaker:
    @outer
    def __init__(self):
        self.fake = Faker("zh_CN")

    @outer
    def Create_Data(self):
        name = self.fake.name() + '(测试)'
        return {
            'account': name,
            'address': '',
            'latitude': '',
            'longitude': '',
            'name': name,
            'phone': self.fake.phone_number(),
            'range': '',
            'realName': name,
            'role': 1,
            'addressSwitch': 2,
            'pwd': self.fake.password(),
        }


class Circle:

    @outer
    def __init__(self):
        self.token = login()['data']['token']
        self.url = 'https://api.admin.merchant.java.crmeb.net/api/admin/platform/circle'
        self.headers = {'authori-zation': self.token, 'content-type': 'application/json'}
        self.faker = BaseFaker()

    @outer
    def selent(self):
        url = self.url + '/list/tree'
        headers = self.headers
        response = requests.get(url, headers=headers, )
        return response.json()

    @outer
    def add(self):
        url = self.url + '/save'
        headers = self.headers
        json_data = self.faker.Create_Data()
        response = requests.post(url, headers=headers, json=json_data, )
        logger.info(response.json())
        return {'response': response.json(), 'test_data': json_data}

    @outer
    def delete(self, del_id):
        url = self.url + f'/delete/{del_id}'
        headers = self.headers
        response = requests.post(url, headers=headers, )
        logger.info(response.json())
        return response.json()


if __name__ == '__main__':
    circle = Circle()
    add_result = circle.add()
    save_id = add_result['response']['data']
    test_data = add_result['test_data']
    data = circle.selent()
    assert jmespath.search("data[?id == `{}`].realName".format(save_id), data)[0] == test_data['realName']
    Circle().delete(save_id)
